package xyz.robinbingo.leetcode.a20.b06.c05;

public class Solution {
    public int[] spiralOrder(int[][] matrix) {
        int row = matrix.length;
        if (row == 0) {
            return new int[0];
        }
        int col = matrix[0].length;
        if (col == 0) {
            return new int[0];
        }
        int size = row * col;
        int[] result = new int[size];
        int cur = 0;
        for (int i = 0; i <= Math.min(row, col) / 2; i++) {
            int j = i, k = i;
            while (cur < size && k < col - i) {
                result[cur++] = matrix[j][k];
                k++;
            }
            j++;
            k--;
            while (cur < size && j < row - i) {
                result[cur++] = matrix[j][k];
                j++;
            }
            j--;
            k--;
            while (cur < size && k >= i) {
                result[cur++] = matrix[j][k];
                k--;
            }
            j--;
            k++;
            while (cur < size && j > i) {
                result[cur++] = matrix[j][k];
                j--;
            }
        }
        return result;
    }
}